package org.oschina.security;

import org.apache.commons.lang.ObjectUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.oschina.Constants;
import org.oschina.handler.BaseAopHandler;
import org.oschina.helper.ThreadVariableHelper;
import org.oschina.security.annotation.Require;
import org.oschina.security.impl.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 认证注解处理
 */
@Component
@Aspect
public class SecurityHandler extends BaseAopHandler implements Ordered {

	@Autowired
	private ISecurity security;
	@Autowired
	private ThreadVariableHelper threadVariableHelper;
	
	@Pointcut("@annotation(org.oschina.security.annotation.Require)")
	public void aroundPoint(){};
	
	@Around(value="aroundPoint()")
	public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable
	{
		Require require=(Require)getAnnotation(proceedingJoinPoint, Require.class);
		
		//权限不通过
		if(!security.require(require.authorization(), getToken(), require.or()))
			throw new UnauthorizedException();
		
		return proceedingJoinPoint.proceed();
	}

	@Override
	public int getOrder()
	{
		return 15;
	}
	
	private String getToken()
	{
		return ObjectUtils.toString(threadVariableHelper.get(Constants.THREAD_VARIABLE_TOKEN));
	}
}